import Dispatcher from '../core/Dispatcher';
import ActionTypes from '../constants/ActionTypes';
import StoreCommon    from "./StoreCommon";
import assign         from "object-assign";
import _              from "lodash";

var _users = [];
var _page = 1;
var _loading = false;

function loadUsers(data){
  _users = _users.concat(JSON.parse(data).data);
  _loading = false;
  nextPage();
}

function nextPage() {
  _page = _page + 1;
}

function loading() {
  _loading = true;
}

var StoryStore = assign({}, StoreCommon, {
  getAll() {
    return _users;
  },

  nextPage() {
    return _page;
  },

  loading() {
    return _loading;
  },
});

// Register callback with Dispatcher
Dispatcher.register(function(payload) {
  var action = payload.action;

  switch(action){

    case ActionTypes.RECEIVE_STORIES:
      loadUsers(payload.data.text);
      break;

    case ActionTypes.LOAD_STORIES:
      loading();
      break;

    default:
      return true;
  }
  // If action was responded to, emit change event
  StoryStore.emitChange();

  return true;

});

export default StoryStore;
